package com.itheima.nio.tomcat.process;

import com.itheima.nio.tomcat.domain.HttpRequest;
import com.itheima.nio.tomcat.domain.HttpResponse;
import com.itheima.nio.tomcat.inter.HttpServlet;
import com.itheima.nio.tomcat.inter.ServletConcurrentHashMap;
import com.itheima.nio.tomcat.servlet.AServlet;
import com.itheima.nio.tomcat.servlet.BServlet;
import com.itheima.nio.tomcat.servlet.CServlet;
import com.itheima.nio.tomcat.servlet.UserServlet;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;

public class DynamicResourceProcess {

    public void process(HttpRequest httpRequest, HttpResponse httpResponse){

        String requestURI = httpRequest.getRequestURI();
        HttpServlet httpServlet = ServletConcurrentHashMap.concurrentHashMap.get(requestURI);
        if (httpServlet != null){
            httpServlet.service(httpRequest, httpResponse);
        } else {
            response404(httpResponse);
        }
//        if (httpRequest.getRequestURI().equals("/servlet/AServlet")){
//            AServlet aServlet = new AServlet();
//            aServlet.service(httpRequest, httpResponse);
//        } else if (httpRequest.getRequestURI().equals("/servlet/UserServlet")){
//            UserServlet userServlet = new UserServlet();
//            userServlet.service(httpRequest, httpResponse);
//        } else if (httpRequest.getRequestURI().equals("/servlet/BServlet")){
//            BServlet bServlet = new BServlet();
//            bServlet.service(httpRequest, httpResponse);
//        } else if (httpRequest.getRequestURI().equals("/servlet/CServlet")){
//            CServlet cServlet = new CServlet();
//            cServlet.service(httpRequest, httpResponse);
//        }
    }

    private void response404(HttpResponse httpResponse) {
        String responseLine = "HTTP/1.1 404 NOT FOUND\r\n";
        String responseHeader = "Content-Type: text/html;charset=UTF-8\r\n";
        String emptyLine = "\r\n";
        String responseLineAndHeaderAndEmptyLine = responseLine + responseHeader + emptyLine;
        SelectionKey selectionKey = httpResponse.getSelectionKey();
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
        try {
            ByteBuffer byteBuffer = ByteBuffer.wrap(responseLineAndHeaderAndEmptyLine.getBytes("UTF-8"));
            socketChannel.write(byteBuffer);
            socketChannel.write(ByteBuffer.wrap("404 NOT FOUND....".getBytes("UTF-8")));
            socketChannel.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
